package com.itheima.tlias.aspect;


import com.itheima.tlias.annotation.LogOperate;
import com.itheima.tlias.mapper.OperateLogMapper;
import com.itheima.tlias.pojo.OperateLog;
import com.itheima.tlias.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class OperateLogAspect {
    @Resource
    private OperateLogMapper operateLogMapper;

    /**
     * 切面方法<p>
     * 环绕通知
     *
     * @param joinPoint 切点
     * @param log       注解
     * @return Object
     * @throws Throwable 抛出异常
     */
    //直接获取注解
    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint joinPoint, LogOperate log) throws Throwable {
        // 开始时间
        long startTime = System.currentTimeMillis();
        // 执行方法
        Object result = joinPoint.proceed();
        // 结束时间
        long endTime = System.currentTimeMillis();
        // 耗时
        long costTime = endTime - startTime;
        /*
         * 使用builder模式构建日志对象
         * 设置当前登录用户id、当前时间
         * 设置类名、方法名、参数、返回值、耗时
         */
        OperateLog operateLog = OperateLog.builder()
                .operateEmpId(getCurrentUserId())
                .operateTime(LocalDateTime.now())
                .className(joinPoint.getTarget().getClass().getName())
                .methodName(joinPoint.getSignature().getName())
                .methodParams(Arrays.toString(joinPoint.getArgs()))
                .returnValue(result != null ? result.toString() : "null")
                .costTime(costTime)
                .build();
        // 插入日志
        operateLogMapper.addLogs(operateLog);
        return result;
    }

    /**
     * 获取当前登录用户id
     *
     * @return id
     */
    private int getCurrentUserId() {
        return CurrentHolder.getCurrentId();
    }

}
